<?php
/**
 * Handles any global user data,
 * such as private messages, friends/ignores
 * etc..
 * 
 * @author Mark Dohmen.
 */
final class Login {
	
	/**
	 * Instance of this class.
	 */
	private static $login = NULL;
	
	/**
	 * The world list.
	 */
	private $worldList;
	
	/**
	 * Class Constructor..
	 */
	final public function Login() {
		WorldLoader::getWorldLoader()->load();
	}
	
	/**
	 * The login method.
	 *
	 * TODO: Load more global data(e.g. email, 
	 * private messages etc..)
	 *
	 * @param $username
	 * @param $password
	 * @param $worldId
	 */
	final public function login(string $username, string $password, int $worldId) {
		if (checkUserLoggedIn()) {
			return (boolean) true;
		}
		$world = WorldLoader::getWorldLoader()->getWorldByID($worldId);
		$username = DatabaseUtils::filter($username);
		$password = DatabaseUtils::filter($password);
		$password = sha1(md5(Constants::GAME_SESSION_KEY) . sha1($password . $username));
		$count = Database::getDatabase()->numRows("SELECT * FROM `accounts` WHERE `username`='" . $username . "' AND `password`='" . $password . "'");
		if ($count != 1) {
			return (string) "Incorrent login credentials.";
		}
		$this->startSession();
		$_SESSION['username'] = $username;
		$_SESSION['worldId'] = $worldId;
		Database::getDatabase()->connect($world);
		return (boolean) true;
	}
	
	/**
	 * Start a session.
	 */
	final private function startSession() {
		try {
			session_start();	
		} catch (Exception $e) {
			
		}
	}
	
	/**
	 * Check if a user is logged in or not.
	 *
	 * @return true/false
	 */
	final public function checkUserLoggedIn() {
		$this->startSession();
		if (isset($_SESSION['user'])) {
			return (boolean) true;
		}
		return (boolean) false;
	}
	
	/**
	 * Gets the world id.
	 *
	 * @return $worldId/null
	 */
	final public function getWorldId() {
		$this->startSession();
		if (isset($_SESSION['worldId'])) {
			return (int) $_SESSION['worldId'];
		}
		return NULL;
	}
	
	/**
	 * Gets the instance of login.
	 *
	 * @return $login/null
	 */
	final public static function getLogin() {
		if (!(self::$login instanceof Login)) {
			self::$login = new Login();
		}
		return (object) self::$login;
	}
	
	/**
	 * Gets the world list.
	 *
	 * @param $worldList
	 */
	final public function getWorldList() {
		return (array) $this->worldList;	
	}
}
?>